import {
  ModalForm,
  ProForm,
  ProFormText,
  ProFormCheckbox,
  ProFormTextArea,
  ProFormUploadButton,
} from '@ant-design/pro-components';
import { message } from 'antd';
import { postMemberEdit } from '../../request';
import * as React from 'react';
import { useRef } from 'react';
import type { ProFormInstance } from '@ant-design/pro-components';
import { useAsyncEffect } from 'ahooks';
import { useIntl } from '@umijs/max';

interface FormType {
  avatar: any;
  username: string;
  realName: string;
  mobile: string;
  password?: string;
  remark: string;
  permissionStrings: Array<string> | string;
}

const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

export default (props: {
  visible: boolean;
  id: number;
  info: FormType | null;
  onCancel: () => void;
  done: () => void;
}) => {
  const { visible, id, onCancel, done, info } = props;



  const intl = useIntl();
  const formRef = useRef<ProFormInstance>(null);

  useAsyncEffect(async () => {
    await waitTime(50);

    if (visible && id) {
      if (info) {
        formRef?.current?.setFieldsValue({
          username: info.username,
          realName: info.realName,
          mobile: info.mobile,
          password: info.password,
          remark: info.remark,
          permissionStrings: info.permissionStrings,
        });
      }
    }
  }, [visible, id]);

  const toString = (value: string | Array<string>): string => {
    if (typeof value === 'string') {
      return value;
    } else if (Array.isArray(value)) {
      return value.join(',');
    } else {
      return 'Invalid input';
    }
  };

  const plainOptions = [
    { label: intl.formatMessage({id:"SetUser.account"}), value: '1' },
    { label: intl.formatMessage({id:"SetUser.ChecknHistory"}), value: '2' },
    { label: intl.formatMessage({id:"SetUser.CardIssuance"}), value: '3' },
    { label: intl.formatMessage({id:"SetUser.DoorOpening"}), value: '4' },
    // { label: '监控', value: '5' },
    { label:intl.formatMessage({id:"SetUser.FixLock"}), value: '6' },
    { label: intl.formatMessage({id:"SetUser.setting"}), value: '7' },
  ];

  const onFinish = async (values: FormType): Promise<boolean> => {
    await waitTime(500);
    const res: any = await postMemberEdit({
      ...values,
      permissionStrings: toString(values.permissionStrings),
      passwordHash: '',
      avatar: '',
      id,
    });
    if (res.code !== 0) return message.error(res.msg);
    message.success(res.msg);
    onCancel();
    done();
    return true;
  };
const changeca = (value: string | string[]) =>{
if(!value.includes("1")){
  message.error(intl.formatMessage({ id: 'SetUser.Prohibit permissions.' }))
  let arr = formRef.current?.getFieldValue("permissionStrings")
  arr.push("1")
  formRef.current?.setFieldValue("permissionStrings",arr)
}
  
}
  return (
    <ModalForm<FormType>
      formRef={formRef}
      open={visible}
      title={id ? intl.formatMessage({ id: 'SetUser.Edit user' }) : intl.formatMessage({ id: 'SetUser.New user' })}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
        onCancel: () => onCancel(),
      }}
      submitTimeout={2000}
      onFinish={(values) => onFinish(values)}
    >
      <ProForm.Group>
        <ProFormUploadButton
          name="avatar"
          label={intl.formatMessage({ id: 'SetUser.Avatar' })}
          max={1}
          fieldProps={{
            name: 'file',
            listType: 'picture-card',
          }}
          action="/upload.do"
          extra=""
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormText
          width="md"
          name="username"
          label={intl.formatMessage({ id: 'SetUser.Username' })}
          placeholder={intl.formatMessage({ id: 'SetUser.Please username.' })}
          rules={[
            { required: true, message: intl.formatMessage({ id: 'SetUser.Please username.' }) },
            {
              pattern: new RegExp('^[a-zA-Z0-9\\-_]{4,}$'),
              message: intl.formatMessage({ id: 'SetUser.valid username' }),
            },
          ]}
        />
        <ProFormText
          width="md"
          name="realName"
          label={intl.formatMessage({ id: 'SetUser.Real Name' })}
          placeholder={intl.formatMessage({ id: 'SetUser.Please real name.' })}
          rules={[{ required: true, message: intl.formatMessage({ id: 'SetUser.Please real name.' }) }]}
        />
      </ProForm.Group>
      <ProForm.Group>
      <ProFormText.Password
          width="md"
          label={intl.formatMessage({ id: 'SetUser.Password' })}
          name="password"
          placeholder={id ? intl.formatMessage({ id: 'SetUser.Password unchanged' }) : intl.formatMessage({ id: 'SetUser.Please password.' })}
          rules={
            id
              ? []
              : [
                  { required: true, message: intl.formatMessage({ id: 'SetUser.Please password.' }) },
                  {
                    pattern: new RegExp('^[a-zA-Z0-9\\-_]{6,}$'),
                    message: intl.formatMessage({ id: 'SetUser.valid password' }),
                  },
                ]
          }
        />  
        <ProFormText
          width="md"
          name="mobile"
          label={intl.formatMessage({ id: 'SetUser.Mobile' })}
          placeholder={intl.formatMessage({ id: 'SetUser.Please mobile.' })}
          // rules={[
          //   { required: true, message: '请输入手机号' },
          //   {
          //     pattern: new RegExp(
                
          //       '^\\d{11}$',
          //     ),
          //     message: '手机号格式不合法',
          //   },
          // ]}
        />

      </ProForm.Group>
      <ProForm.Group>
        <ProFormCheckbox.Group
          name="permissionStrings"
          layout="horizontal"
          label={intl.formatMessage({ id: 'SetUser.Permission' })}
          onChange={changeca}
          initialValue={['1']} // 设置默认选中的值
          options={plainOptions}
          rules={[{ required: true, message:intl.formatMessage({ id: 'SetUser.Please permission.' }) }]}
        />
      </ProForm.Group>
      <ProForm.Group>
        <ProFormTextArea width="lg" name="remark" label={intl.formatMessage({ id: 'SetUser.Remark' })} placeholder={intl.formatMessage({ id: 'SetUser.Please remark.' })} />
      </ProForm.Group>
    </ModalForm>
  );
};
